<?php

namespace App\Http\Controllers\Api;

use App\Models\PrizeRecord;
use Illuminate\Http\Request;
use App\Http\Requests\Api\PrizeRecordRequest;
use App\Transformers\PrizeRecordTransformer;

class PrizeRecordsController extends Controller
{
    public function search(Request $request, PrizeRecord $prizeRecord)
    {
        $per_page = $request->input('per_page', 20);
        $query = $prizeRecord->query();

        $query->where('delflag', false);

        if ($prize_id = $request->prize_id) {
            $query=$query->where('prize_id', $request->prize_id);
        }

        if ($user_id = $request->user_id) {
            $query=$query->where('user_id', $request->user_id);
        }

        if ($filiale_id = $request->filiale_id) {
            $query=$query->where('filiale_id', $request->filiale_id);
        }

        if (($redeem_begin = $request->redeem_begin) && ($redeem_end = $request->redeem_end)) {
            $query=$query->where('redeem_at', '>=', $request->redeem_begin);
            $query=$query->where('redeem_at', '<=', $request->redeem_end);
        }

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $prizeRecords = $query->paginate($per_page);

        return $this->response->paginator($prizeRecords, new PrizeRecordTransformer());
    }

	public function index(Request $request, PrizeRecord $prizeRecord)
    {
        $per_page = $request->input('per_page', 20);
        $query = $prizeRecord->query();

        $query->where('delflag', false);

        if ($orderBy = $request->orderBy) {
            $query=$query->ordered();
        } else {
            $query=$query->recent();
        }

        $prizeRecords = $query->paginate($per_page);

        return $this->response->paginator($prizeRecords, new PrizeRecordTransformer());
    }

    public function userIndex(Request $request)
    {
        $per_page = $request->input('per_page', 20);

        $prizeRecords=null;

        if ($orderBy = $request->orderBy) {
            $prizeRecords = $this->user->prizeRecords()->where('delflag', false)->ordered()
                ->paginate($per_page);
        } else {
            $prizeRecords = $this->user->prizeRecords()->where('delflag', false)->recent()
                ->paginate($per_page);
        }

        return $this->response->paginator($prizeRecords, new PrizeRecordTransformer());
    }

    public function show((Prize $prize, PrizeRecord $prizeRecord)
    {
        return $this->response->item($prizeRecord, new PrizeRecordTransformer());
    }

	public function store(PrizeRecordRequest $request, Prize,$prize, PrizeRecord $prizeRecord)
    {
        if ( (!$prize) !! ($prize->quantity<1) ) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'奖品不存在或已兑完！',
            ])->setStatusCode(400);
        }
        $tempdate=\Carbon\Carbon::now()->toDateTimeString();

        if (($prize->redeeming_begin<=$tempdate) && ($prize->redeeming_end>=$tempdate)) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'兑换奖品当前不能兑换！',
            ])->setStatusCode(400);
        }

        $user=$this->user;

        //查询已兑数量
        $prizeRecords=$user->prizeRecords->where('prize_id', $prize->id)->where('delflag', false);
        if ($prizeRecords->count()>=$prizeRecord->user_redeeming_quantity) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'兑换奖品数量达到上限！',
            ])->setStatusCode(400);
        }


        // 开启事务
        \DB::transaction(function () use ($prize, $user,$prizeRecord) {
            $prize->decrement('remain_quantity');
            $prize->increment('redeeming_quantity');

            $prizeRecord->prize_id=$prize->id;
            $prizeRecord->user_id=$user->id;
            $prizeRecord->redeem_code=str_random(15);
            $prizeRecord->save();
            //加扣积分的逻辑 成功执行，错误throw exception
        });
		return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'兑奖成功',
        ])->setStatusCode(201);
	}

	public function update(PrizeRecordRequest $request, Prize $prize, PrizeRecord $prizeRecord)
	{
        $prizeRecord->update($request->all());

		return $this->response->item($prizeRecord, new PrizeRecordTransformer());
	}

	public function destroy(Prize $prize, PrizeRecord $prizeRecord)
	{
        if ( (!$prizeRecord) || ($prizeRecord->delflag)) {
             return $this->response->array([
                    'status'=>false,
                    'data'=>[
                        'successflag'=>false,
                    ],
                    'message'=>'删除失败',
                ])->setStatusCode(400);
        }

		$prizeRecord->delflag=true;
        //操作quality
        //返回积分的逻辑 成功执行，错误throw exception
        $prizeRecord->save();

		return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'删除成功',
        ])->setStatusCode(200);
	}

    public function adminRedeemed(Request $request, Prize $prize, PrizeRecord $prizeRecord)
    {
        if ( (!$prizeRecord) || ($prizeRecord->delflag)) {
             return $this->response->array([
                    'status'=>false,
                    'data'=>[
                        'successflag'=>false,
                    ],
                    'message'=>'领奖失败',
                ])->setStatusCode(400);
        }

        if (hash_equals($prizeRecord->redeem_code, $request->redeem_code)){

             // 开启事务
            \DB::transaction(function () use ($request, $prize, $prizeRecord) {
                $prize->increment('redeemed_quantity');

                $prizeRecord->filiale_id=$request->filiale_id;
                $prizeRecord->user_id=$request->user_id;
                $prizeRecord->redeemflag=true;
                $prizeRecord->redeem_at=\Carbon\Carbon::now()->toDateTimeString();
                $prizeRecord->save();

                //添加redeemlog
                RedeemLog::create([
                    'company_userid' => $this->user->id,
                    'user_id' => $request->user_id,
                    'prize_id' => $prize->id,
                    'filiale_id'=> $request->user_id,
                    'remark'=> $request->input('remark', ''),
                ]);
            });


            return $this->response->array([
                'status'=>true,
                'data'=>[
                    'successflag'=>true,
                ],
                'message'=>'领奖登记成功',
            ])->setStatusCode(200);
        }

        return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'领奖登记失败',
            ])->setStatusCode(400);
    }

    public function userRedeemed(Request $request, Prize $prize, PrizeRecord $prizeRecord)
    {
        if ( (!$prizeRecord) || ($prizeRecord->delflag)) {
             return $this->response->array([
                    'status'=>false,
                    'data'=>[
                        'successflag'=>false,
                    ],
                    'message'=>'领奖失败',
                ])->setStatusCode(400);
        }

        if (hash_equals($prizeRecord->redeem_code, $request->redeem_code)){

             // 开启事务
            \DB::transaction(function () use ($request, $prize, $prizeRecord) {
                $prize->increment('redeemed_quantity');

                $prizeRecord->filiale_id=$request->filiale_id;
                $prizeRecord->user_id=$this->user->id;
                $prizeRecord->redeemflag=true;
                $prizeRecord->redeem_at=\Carbon\Carbon::now()->toDateTimeString();
                $prizeRecord->save();

                //添加redeemlog
                RedeemLog::create([
                    'company_userid' => $request->company_userid,
                    'user_id' => $this->user->id,
                    'prize_id' => $prize->id,
                    'filiale_id'=> $request->user_id,
                    'remark'=> $request->input('remark', ''),
                ]);
            });

            return $this->response->array([
                'status'=>true,
                'data'=>[
                    'successflag'=>true,
                ],
                'message'=>'领奖登记成功',
            ])->setStatusCode(200);
        }

        return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'领奖登记失败',
            ])->setStatusCode(400);
    }

    public function userRedeeming(Prize,$prize, PrizeRecord $prizeRecord)
    {
        if ( (!$prize) !! ($prize->quantity<1) ) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'奖品不存在或已兑完！',
            ])->setStatusCode(400);
        }
        $tempdate=\Carbon\Carbon::now()->toDateTimeString();

        if (($prize->redeeming_begin<=$tempdate) && ($prize->redeeming_end>=$tempdate)) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'兑换奖品当前不能兑换！',
            ])->setStatusCode(400);
        }

        $user=$this->user;

        //查询已兑数量
        $prizeRecords=$user->prizeRecords->where('prize_id', $prize->id)->where('delflag', false);
        if ($prizeRecords->count()>=$prizeRecord->user_redeeming_quantity) {
            return $this->response->array([
                'status'=>false,
                'data'=>[
                    'successflag'=>false,
                ],
                'message'=>'兑换奖品数量达到上限！',
            ])->setStatusCode(400);
        }


        // 开启事务
        \DB::transaction(function () use ($prize, $user,$prizeRecord) {
            $prize->decrement('remain_quantity');
            $prize->increment('redeeming_quantity');

            $prizeRecord->prize_id=$prize->id;
            $prizeRecord->user_id=$user->id;
            $prizeRecord->redeem_code=str_random(15);
            $prizeRecord->save();

            //加扣积分的逻辑 成功执行，错误throw exception
        });
        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'兑奖成功',
        ])->setStatusCode(201);
    }
}